package com.dhcc.android.base.gis;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.PointF;
import android.view.MotionEvent;
import android.view.View;
import android.widget.PopupWindow;

import com.dhcc.android.base.R;
import com.dhcc.android.base.utils.CommenUtil;
import com.dhcc.android.base.utils.Constants;

import java.util.List;

import srs.DataSource.Vector.SearchType;
import srs.Display.IScreenDisplay;
import srs.Element.IPicElement;
import srs.GPS.GPSControl;
import srs.GPS.GPSConvert;
import srs.Geometry.IEnvelope;
import srs.Geometry.IPoint;
import srs.Geometry.srsGeometryType;
import srs.Layer.IFeatureLayer;
import srs.tools.BaseControl;
import srs.tools.BaseTool;

//import com.ths.animation.AnimationControl;

/**
 * @author 目标对象的点选
 * @author lzy
 */
public class TouchLongTool extends BaseTool {

    /**
     * 选中目标后的弹窗。 可以根据需要，使用您自己的弹窗； 如屏幕不弹出弹窗，亦可舍弃此项；
     */
    public PopupWindow mTouchLongPop;

    /**
     *
     */
    private PointF mCurrentPoint = null;
    private IPoint mPFT = null;
    private IScreenDisplay mScreenDisplay;
    private static IFeatureLayer mLayer;
    /* private List<Integer> mAllfids; */
    private Paint mPaint;
    /**
     * 点选时间控制，手指在屏幕上停留最少多久，视为点选操作 可根据业务需要，手动设置此项属性
     * 此属性也可通过系统配置设置，系统设置修改时，调用此属性进行修改
     */
    private static long LONGTIME = 10;
    /**
     * 点选距离控制，触摸点与目标点最远相聚多少时，可视为选中 可根据业务需要，手动设置此项属性
     * 此属性也可通过系统配置设置，系统设置修改时，调用此属性进行修改
     */
    public static float Dis = 10;
    /* private Bitmap mbitmap; */
    private static String mTitleStr = "详细信息";
    /**
     * MapControl输出的底图
     */
    Bitmap mBitExMap = null;

    /**
     * 在此添加选中目标后会触发的动作；
     */
    public SelectItemChangedListener zoom2Selected = null;

    /**
     * 判断定位辅助变量：记录“ACTION_DOWN”时手指的屏幕位置
     */
    private int xposition = 0;
    private int yposition = 0;

    /**
     * 手指触摸屏幕的时刻
     */
    private long mExtTime = -1;

    /**
     * 是否为选择单条记录
     */
    public boolean IsOnlyOneSelect = true;

    /**
     * 是否为一次性选择
     */
    public boolean IsOnlyOneTime = true;

    public TouchLongTool(IFeatureLayer TargetLayer) {
        zoom2Selected = null;
        mLayer = TargetLayer;

        mPaint = new Paint();
        mPaint.setColor(Color.YELLOW);
        mPaint.setStrokeWidth(2);
        mPaint.setStyle(Style.FILL);

        super.setRate();
        if (mLayer != null) {
            if (mLayer.getFeatureClass().getGeometryType() == srsGeometryType.Point) {
                Dis = 30; // 若目标类型为“点”，则缓冲距离为30
            } else {
                Dis = 10; // 若目标类型为“线、面”缓冲距离为10
            }
        }
    }

    @Override
    public String getText() {
        return mTitleStr;
    }

    @Override
    public Bitmap getBitmap() {
        return null;
    }

    public BaseControl getBuddyControl() {
        return this.mBuddyControl;
    }

    public void setBuddyControl(BaseControl value) {
        if (value != null) {
            this.mBuddyControl = value;
            mBuddyControl.getActiveView().FocusMap().getSelectionSet()
                    .ClearSelection();
        }
    }

    @Override
    public void onClick(View v) {
        try {
            super.onClick(v);
            /*
			 * LayoutInflater
			 * flater=(LayoutInflater)v.getContext().getSystemService
			 * (Context.LAYOUT_INFLATER_SERVICE);
			 * ((IFeatureLayer)_BuddyControl.getActiveView
			 * ().FocusMap().getActiveLayer
			 * ()).FeatureClass().SelectionSet(null);
			 * _BuddyControl.getActiveView
			 * ().FocusMap().SelectionSet().ClearSelection();
			 */
            if (this.mBuddyControl instanceof BaseControl) {
                mScreenDisplay = this.mBuddyControl.getActiveView().FocusMap()
                        .getScreenDisplay();
            }
            mEnable = true;
            mBuddyControl.setDrawTool(this);
            mBuddyControl.PartialRefresh();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mBitExMap = mBuddyControl.getActiveView().FocusMap()
                        .ExportMap(false);
                if (mExtTime == -1) {
                    mExtTime = System.currentTimeMillis();
                    mCurrentPoint = new PointF(event.getX() * mRate, event.getY()
                            * mRate);
                }
                xposition = (int) event.getX();
                yposition = (int) event.getY();
                break;
            case MotionEvent.ACTION_UP:
                try {
                    GPSControl mGPSControl = GPSControl.getInstance();
                    double latitude = mGPSControl.GPSLatitude;
                    double longitude = mGPSControl.GPSLongitude;
                    String latlon = String.valueOf(latitude) + ","
                            + String.valueOf(longitude);
                    System.out.println("--------------------" + latlon);
                    if (event.getPointerCount() == 1
				/*
				 * mExtTime!=-1&&System.currentTimeMillis()-mExtTime>LONGTIME
				 * &&Math.abs(event.getX()-xposition)<5
				 * &&Math.abs(event.getY()-yposition)<5
				 */) {
                        // 长按 将图上位置转换成地理位置
                        super.onTouch(v, event);
                        mExtTime = -1;
                        PointF pF = new PointF(event.getX() * mRate, event.getY()
                                * mRate);
                        IPoint selGeo = mBuddyControl.ToWorldPoint(new PointF(pF.x,
                                pF.y));

                        // 保存点击的位置，作为导航目标点用
                        // edit by 李忠义
                        // 20150616
                        Constants.TargetXY = GPSConvert.PROJECT2GEO(selGeo.X(),
                                selGeo.Y(), mBuddyControl.getActiveView()
                                        .FocusMap().getGeoProjectType());
                        Constants.TargetPointTouch = selGeo;

                        int index = -1;
                        IPicElement picElement = null;
                        if (mCurrentPoint != null
                                && Math.abs(mCurrentPoint.x - pF.x) < Dis
                                && Math.abs(mCurrentPoint.y - pF.y) < Dis) {
                            // 在一个点位，此时才算“长点击”
                            List<Integer> sels = ((IFeatureLayer) mLayer)
                                    .getFeatureClass().SelectOnlyOne(selGeo,
                                            SearchType.Intersect,
                                            mScreenDisplay.ToMapDistance(Dis));
                            if (sels != null && sels.size() > 0) {
                                mExtTime = -1;
                                mCurrentPoint = null;
                                // 将控件上显示的视图设置为绘制了“选择框”的视图。
							/*
							 * SelectedFeatures s = new SelectedFeatures();
							 * s.FeatureClass = ((IFeatureLayer) mLayer)
							 * .getFeatureClass(); s.FIDs = sels;
							 * mBuddyControl.getActiveView().FocusMap()
							 * .getSelectionSet().ClearSelection();
							 * mLayer.getFeatureClass().setSelectionSet(s.FIDs);
							 * index = s.FIDs.get(0);
							 */
                                index = sels.get(0);

							/*
							 * 写在gotoNext中了
							 * CommenUtil.setLightSelected((IFeatureLayer)
							 * mLayer,index,(MapControl)mBuddyControl,selGeo);
							 */

                                // 选中目标后，会触发在zoom2Selected中注册的事件。
                                if (zoom2Selected != null) {
                                    // index为选中对象的FID（选中对象行的顺序号）
                                    zoom2Selected.doEventSettingsChanged(index);
                                }
                                // 选中对象时，设置对象中心点的小圆点
                                // 根据需要，可自行处理；若不需要显示中心点可删除此端代码
                                // MapShowControler.TargetPoint =
                                // mLayer.FeatureClass().GetGeometry(index).CenterPoint();
                                // picElement = new PicElement();
                                // picElement.setPic(MapShowControler.BitmapTarget,
                                // -MapShowControler.BitmapTarget.getWidth()/2,
                                // -MapShowControler.BitmapTarget.getHeight());
                                // picElement.Geometry(MapShowControler.TargetPoint);
                                // 在工程管理中设置操作图层的选中条目
                                // 根据业务需要，若没有用处可去掉词句。
                                // GlobalTaskCollection.getSelectedWholeTask().setSelectedTaskLayerFID(index);
                                // 点击地图时，都会触发的事件，
                                // 为便于管理，集中于一处了，根据需要可自行调整
                                // MapShowControler.setZoomTo(index);
                                // 点击对象时，设置对象中心点的小圆点
                                // 根据需要，可自行处理；若不需要显示中心点可删除此段代码
                                // _BuddyControl.getElementContainer().ClearElement();
                                // _BuddyControl.getElementContainer().AddElement(picElement);
                                // 刷新屏幕
                                mBuddyControl.Refresh();
                            } else {
                                // 设置地图为未选中任何对象
                                mBuddyControl.getActiveView().FocusMap()
                                        .getSelectionSet().ClearSelection();
                                // 点击地图上某点时，设置点击位置的小圆点
                                // 根据需要，可自行处理；若不需要显示点击位置可删除此段代码
                                // MapShowControler.TargetPoint =
                                // _BuddyControl.ToWorldPoint(new
                                // PointF(event.getX(),event.getY()));
                                // picElement = new PicElement();
                                // picElement.setPic(MapShowControler.BitmapTarget,
                                // -MapShowControler.BitmapTarget.getWidth()/2,
                                // -MapShowControler.BitmapTarget.getHeight());
                                // picElement.Geometry(MapShowControler.TargetPoint);
                                // 设置当前操作图层为未选中任何对象
							/* mLayer.getFeatureClass().setSelectionSet(null); */
                                // 点击地图上某点时，设置点击位置的小圆点
                                // 根据需要，可自行处理；若不需要显示点击位置可删除此段代码
							/*
							 * mBuddyControl.getElementContainer().ClearElement()
							 * ; mBuddyControl.getElementContainer().AddElement(
							 * picElement);
							 */
                                // 刷新屏幕
                                // _BuddyControl.PartialRefresh();

                                IEnvelope envOldEnvelope = mBuddyControl
                                        .getActiveView().FocusMap().getExtent();
							/*
							 * added by lizhongyi 20150626 若未选中任何目标，则标示符自动移动至点击处
							 */
                                mBuddyControl.getElementContainer().RemoveElement(
                                        mBuddyControl.getElementContainer()
                                                .getElementCount() - 1);

							/* 添加选中目标点位 */
                                picElement = new srs.Element.PicElement();
                                if (CommenUtil.BitmapTarget == null) {
                                    CommenUtil.BitmapTarget = BitmapFactory
                                            .decodeResource(mBuddyControl
                                                            .getContext().getResources(),
                                                    R.mipmap.target);
                                }
                                picElement.setPic(CommenUtil.BitmapTarget,
                                        -CommenUtil.BitmapTarget.getWidth() / 2,
                                        -CommenUtil.BitmapTarget.getHeight());
                                picElement.setGeometry(selGeo);
                                mBuddyControl.getElementContainer().AddElement(
                                        picElement);
                                mBuddyControl.getActiveView().FocusMap()
                                        .setExtent(envOldEnvelope);
                                mBuddyControl.PartialRefresh();

                            }
                            return true;
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mExtTime = -1;
                mCurrentPoint = null;
                break;
        }
        return false;
    }
}
